<?php
/**
 * 图片上传 
 */
class ImageController extends BaseController
{
    
    const ICON_SIZE = '_192*192';
    private $_userSvc;
    const IMAGE_HOST = "http://59.110.0.207:83";

    public function init()
    {
        parent::init();
        $this->_userSvc = new Service_UserModel();
    }
    
    
    
    //头像上传
    public function uploadAction()
    {
        $login = $this->checkLogin();
        if(!$login){
            $this->redirect('login');
            exit();
        }
        $uid = $login;
        if($this->isPost()){
            $uptypes = array('image/jpg', //上传文件类型列表
                'image/jpeg',
                'image/png',
                'image/pjpeg',
                'image/gif',
                'image/bmp',
                'application/x-shockwave-flash',
                'image/x-png');
            $max_file_size = 5000000;   //上传文件大小限制, 单位BYTE
            $destination_folder = APPLICATION_PATH . '/uploads/' . date("Ymd");  //上传文件路径
            $file = $_FILES["imageInput"];
            if (!is_uploaded_file($_FILES["imageInput"]['tmp_name'])) {
                //是否存在文件
                return array ( 'error'=> 1 , 'msg' => '上传失败');
            }

            if ($max_file_size < $file["size"]) {
                //检查文件大小
                return array ( 'error'=> 1 , 'msg' => '图片过大');
            }
            if (!in_array($file["type"], $uptypes)) {
                //检查文件类型
                return array ( 'error'=> 1 , 'msg' => '图片类型不符');
            }
            if (!file_exists($destination_folder)) {
                mkdir($destination_folder, 0777, true);
            }

            $filename = $file["tmp_name"];
            $pinfo = pathinfo($file["name"]);
            $ext = $pinfo['extension'];
            $imageName = date("YmdHis") . '.' . $ext;  // 重命名文件
            $filepath = $destination_folder . '/' . $imageName;  // 生成文件的绝对路径

            if (!move_uploaded_file($filename, $filepath)) {
                return array ( 'error'=> 1 , 'msg' => '上传失败');
            }else{
                $img_url = '/uploads/' . date("Ymd") . '/' . $imageName;
                $host = 'http://'.$_SERVER['HTTP_HOST'];
                $ret = $this->_userSvc->updateUser( $uid , 'image' ,$host . $img_url );
                if ($ret) {
                    echo json_encode( array ( 'error' => 0 , 'msg' => '上传成功' , 'url' => $host . $img_url ) );
                } else {
                    echo json_encode( array ( 'error' => 2 , 'msg' => '上传失败' ) );
                }
            }
        }
    }
    
}
